<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, onMounted } from "vue";
import {
  ReportPageResponse,
  UpdateReportCommand,
  submitProblemApi
} from "@/api/airport/safetyManage/report.api";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getDeptTree } from "@/api/system/dept";
import {useUserStoreHook} from "@/store/modules/user";

interface Props {
  modelValue: boolean;
  row?: ReportPageResponse;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const deptTree = ref<any[]>([]);

// 转换部门树数据格式
const convertDeptTree = (nodes: any[]) => {
  return nodes.map(node => ({
    value: node.id,
    label: node.label,
    children: node.children ? convertDeptTree(node.children) : undefined
  }));
};

// 获取部门树数据
onMounted(async () => {
  try {
    const { data } = await getDeptTree();
    if (data) {
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});

const formData = reactive<Partial<UpdateReportCommand>>({
  reportId: 0,
  reformRequirement: '', // 整改要求
  actionDeadline: '', // 制定措施期限
  correctiveDeadline: '', // 整改完成期限
  dutyDeptId: undefined, // 责任单位
  dealDeptId: undefined, // 整改单位
  userId: 0,
});

const rules: FormRules = {
  reformRequirement: [
    { required: true, message: "请输入整改要求", trigger: "blur" }
  ],
  actionDeadline: [
    { required: true, message: "请选择制定措施期限", trigger: "change" }
  ],
  correctiveDeadline: [
    { required: true, message: "请选择整改完成期限", trigger: "change" }
  ],
  dutyDeptId: [
    { required: true, message: "请选择责任单位", trigger: "change" }
  ],
  dealDeptId: [
    { required: true, message: "请选择整改单位", trigger: "change" }
  ]
};

const formRef = ref<FormInstance>();

function handleOpened() {
  if (props.row) {
    const userStore = useUserStoreHook(); // 获取用户状态管理实例
    formData.userId = userStore.currentUserInfo?.userId;
    formData.reportId = props.row.reportId;
    formData.dutyDeptId = props.row.dutyDeptId;
    formData.dealDeptId = props.row.acceptDeptId;
  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);

async function handleConfirm() {
  try {
    loading.value = true;
    if (!formRef.value) return;
    await formRef.value.validate();
    const submitData = { ...props.row, ...formData };
    // 调用提交问题接口
    await submitProblemApi(submitData as UpdateReportCommand);
    ElMessage.success("问题提交成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "问题提交失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="'问题提交'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >l
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form-container"
    >
      <el-form-item label="整改要求" prop="reformRequirement">
        <el-input
          v-model="formData.reformRequirement"
          type="textarea"
          :rows="4"
          placeholder="请输入整改要求"
        />
      </el-form-item>
      <el-form-item label="制定措施期限" prop="actionDeadline">
        <el-date-picker
          v-model="formData.actionDeadline"
          type="date"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择制定措施期限"
        />
      </el-form-item>
      <el-form-item label="整改完成期限" prop="correctiveDeadline">
        <el-date-picker
          v-model="formData.correctiveDeadline"
          type="date"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择整改完成期限"
        />
      </el-form-item>
      <el-form-item label="责任单位" prop="dutyDeptId">
        <el-cascader
          v-model="formData.dutyDeptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择责任单位"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="整改单位" prop="dealDeptId">
        <el-cascader
          v-model="formData.dealDeptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择整改单位"
          class="!w-[200px]"
        />
      </el-form-item>
    </el-form>
  </v-dialog>
</template>

<style scoped>
.form-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}
.form-item {
  margin-bottom: 20px;
}
</style>
